package com.xyzwps.mvckotlin.dao.repository

import com.xyzwps.mvckotlin.dao.mapper.IInvitationCodeMapper
import com.xyzwps.mvckotlin.dao.model.InvitationCode
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import org.springframework.stereotype.Repository

@Repository
class InvitationCodeRepository(val invitationCodeMapper: IInvitationCodeMapper) {

    suspend fun getUnusedByCode(code: String): Deferred<InvitationCode?> = coroutineScope {
        async {
            invitationCodeMapper.getUnusedByCode(code)
        }
    }

    suspend fun markAsUsed(code: String): Unit = coroutineScope {
        val job = launch {
            invitationCodeMapper.markAsUsed(code)
        }
        job.join()
    }

    suspend fun countUnusedInvitationCode(): Deferred<Int> = coroutineScope {
        async {
            invitationCodeMapper.countUnusedCode()
        }
    }
}